#!/usr/bin/python
# -*- coding: utf-8 -*-






from django.db import models





class Var(models.Model):
    VAR_TYPES = (
            ('I','int'),
            ('S','string'),
            ('F','float'),
            ('L','list'),
            ('B','boolean'),
            )
    name = models.CharField(unique=False, max_length=240)
    type = models.CharField(max_length=1, choices = VAR_TYPES)
    value=models.TextField(max_length=1024,default=None,blank=True)
    advanced=models.CharField(max_length=240,default=None,null=True,blank=True,help_text=u"Можно использовать ссылку на индекс модели <b>model:sockets.models.Socket</b>, или значение строки в списке значений <b>'1' в списке</b>")
    
    class Meta:
        db_table = u'vars'
        

    def import_class(self, class_string):
        """Returns class object specified by a string.

        Args:
            class_string: The string representing a class.

        Raises:
            ValueError if module part of the class is not specified.
        """
        module_name, _, class_name = class_string.rpartition('.')
        if module_name == '':
            raise ValueError('Class name must contain module part.')
        return getattr(
            __import__(module_name, globals(), locals(), [class_name], -1),
            class_name)


    def get_value(self):
        delimetr=":"
        value=self.value
        if self.type=="L":
            value=self.value.split("<:>")[int(self.advanced)]
        if self.type=="B":
            if self.value=="1" or self.value=="True" or self.value=="Yes":
                value="True"
            if self.value=="0" or self.value=="False" or self.value=="No":
                value="False"
        else:
            value=self.value
        try:
            if "model:" in self.advanced:
                model_name=self.advanced.split(delimetr)[1]#.split(".")[0]
                model=self.import_class(model_name)
                
                #pass
                #from sockets.models import Socket
                selected=model.objects.get(pk=int(self.value))
                value=str(selected)
        except:
            pass
        return value

        
    def __unicode__(self):
        value=self.get_value()
        return u"%s : %s" % (self.name,value)
        
        
class VarGroup(models.Model):
    name = models.CharField(unique=True, max_length=240)
    var = models.ManyToManyField(Var,related_name='u+',help_text=u"Переменные")


    def get_value(self):
        group_list=[]
        for item in self.var.all():
            group_list.append({item.name:str(item.get_value())})
        #print "".join(group_list)
        for i in group_list:
            print i
        return group_list




    def __unicode__(self):
        #value=self.get_value()
        return u"%s" % (self.name,)
        
    class Meta:
        db_table = u'vargroups'
